package com.bcu.cn.onlineexamsystem.user.controller;

import com.bcu.cn.onlineexamsystem.user.entity.Score;
import com.bcu.cn.onlineexamsystem.user.entity.Student;
import com.bcu.cn.onlineexamsystem.user.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    // 教师成绩录入页面
    @GetMapping("/score")
    public String viewScorePage(HttpSession session, Model model) {
        Student user = (Student) session.getAttribute("user");
        if (user == null || !"teacher".equals(user.getRole())) {
            return "redirect:/student/login";
        }
        model.addAttribute("teacherId", user.getUserId());
        return "teacher/score";
    }

    // 教师录入成绩
    @PostMapping("/score")
    public String addScore(@RequestParam String courseId,
                           @RequestParam String studentId,
                           @RequestParam double score,
                           HttpSession session) {
        Student user = (Student) session.getAttribute("user");
        Score scoreObj = new Score();
        scoreObj.setCourseId(courseId);
        scoreObj.setStudentId(studentId);
        scoreObj.setScore(score);
        if (!teacherService.addScore(scoreObj, user.getUserId())) {
            return "redirect:/teacher/score?error=already_exists";
        }
        return "redirect:/teacher/score?success=true";
    }

    // 教师导出成绩报表
    @GetMapping("/export")
    public String exportScores(@RequestParam String courseId, Model model) {
        List<Score> scores = teacherService.exportScores(courseId);
        model.addAttribute("scores", scores);
        return "teacher/export";
    }
}